$(function() {
	init_hashchang();
	$('.nano').nanoScroller();
	init_date_filter();
	init_autocomplete();
	init_map();
	init_price_filters();
	
});

function init_hashchang(){
	new FiltersWidget('filters',PublicUrls['SEARCH_FILTER_EVENT'],'#result_container');

}

function loadEvents(){
	//$(window).trigger('hashchange');
}

function search_event(){
	$.ajax({
	    url: PublicUrls['SEARCH_FILTER_EVENT'],
	    data: $.bbq.getState('filters'),
	    success: function(response){
	    	$('#result_container').html(response);
	    	$('#map').gmap('clearMarkers');
	    	addMarkers();
	    	$('.nano').nanoScroller();
	    },
	    loadingTarget:'#result_container',
		dataType:"html"
	});
}

function load_search_filters(filters_chain){
	var state = $.deparam(filters_chain);
	$.bbq.pushState(state);
	
	//FLATA BINDIAR EL HASHCHANGE PARA QUE POR AJAX LE PEGUE A UN SERVICIO QUE DEVUELVA LOS RESULTADOS 
	
}

function init_map(){
	if($('#latMin').val() && $('#latMax').val()  && $('#lngMin').val()  && $('#lngMax').val()){
		$('#map').gmap({pluginOptions:{afterLoad:loadEvents,fitBounds:create_bound($('#latMin').val(),$('#lngMin').val(),$('#latMax').val(),$('#lngMax').val())},mapEvents:[{event:'idle',action:remove_out_bounds}]});
	}else{
		$('#map').gmap({pluginOptions:{afterLoad:loadEvents},mapEvents:[{event:'idle',action:remove_out_bounds}]});
	}
	
	
	
	$('.event').each(function(index){
		$(this).mouseover(
				function(){
					window.map.markers.getAt(index).setAnimation(google.maps.Animation.BOUNCE)
				}
		)});
	
	$('.event').each(function(index){
		$(this).mouseout(
				function(){
					window.map.markers.getAt(index).setAnimation(null)
				}
		)});
}

function remove_out_bounds(){
	var bounds = window.map.getBounds();
	for(var i=0;i<window.map.markers.length;i++){
		var marker = window.map.markers.getAt(i);
		if(!is_into_bound(bounds,marker.getPosition())){
			$($('.event')[i]).addClass('highlight') ;
		}else{
			$($('.event')[i]).removeClass('highlight') ;
		}
	}
}

function is_into_bound(bound,latLng){
	 return (latLng.lat() > bound.getSouthWest().lat() &&
	            latLng.lat() < bound.getNorthEast().lat() &&
	            latLng.lng() > bound.getSouthWest().lng() &&
	            latLng.lng() < bound.getNorthEast().lng()); 
}

function addMarkers(){
	var maxLat=-999;
	var maxLng=-999;
	var minLat=999;
	var minLng=999;
	for ( var i=0; i<window.markers.length;i++) {
		var marker = window.markers[i];
		var position = create_lat_lng(marker.lat,marker.lng);
		var title = window.markers[i].title;
		$('#map').gmap("addMarker",
				{
					markerOptions:{position:position},
					markerEvents:[{event:'mouseover',action:function(){$('#map').gmap("addInfoWindow",{infoWindowOptions:{content:window.markers[i].title},pluginOptions:{anchor:this}});}}]
				});
		
		if(marker.lat < minLat){
			minLat = marker.lat;
		}
		if(marker.lat > maxLat){
			maxLat = marker.lat;
		}
		
		if(marker.lng < minLng){
			minLng = marker.lng;
		}
		if(marker.lng > maxLng){
			maxLng = marker.lng;
		}
		
	}
	
	window.map.fitBounds(new google.maps.LatLngBounds( new google.maps.LatLng(minLat,minLng),new google.maps.LatLng(maxLat,maxLng)));
}

function init_date_filter(){
	
	var dateFrom = $.bbq.getState('dateFrom');
	var dateTo   = $.bbq.getState('dateTo');
	
	if(dateFrom !=''){
		$("#from").datepicker("setDate", new Date(parseInt(dateFrom)));
	}
	if(dateTo !=''){
		$("#to").datepicker("setDate", new Date(parseInt(dateTo)));
	}
	
	
	$('#date_filters').click(apply_date_filter);
}

function apply_date_filter(){
	
	var dateFilters = new Object()
	
	if($('#from').datepicker( "getDate" ) != undefined) 
		dateFilters.dateFrom =  parseInt($('#from').datepicker( "getDate" ).getTime());
	
	if($('#to').datepicker( "getDate" ) != undefined) 
		dateFilters.dateTo =  parseInt($('#to').datepicker( "getDate" ).getTime());
	
	$.bbq.pushState({'filters':dateFilters});
}

function init_autocomplete(){
	var input = document.getElementById('location');
	var options = {types: ['(cities)']};
	autocomplete = new google.maps.places.Autocomplete(input, options);
	window.geocoder = new google.maps.Geocoder();
	google.maps.event.addListener(autocomplete, 'place_changed', function() {
		 var place = autocomplete.getPlace();
		 $('#locality').val(place.formatted_address);
		 var viewport = place.geometry.viewport;
		 var location_filter = new Object();
		 location_filter.latMin = viewport.getSouthWest().lat();
		 location_filter.latMax = viewport.getNorthEast().lat();
		 location_filter.lngMin = viewport.getSouthWest().lng();
		 location_filter.lngMax = viewport.getNorthEast().lng();
		 
		 $.bbq.pushState({'filters':location_filter});
	}); 
}

function init_price_filters(){
	$('#price_filters').click(apply_price_filters);
}

function apply_price_filters(){
	var filters = new Object();
	
	if($('#priceMax').val() != undefined && $('#priceMax').val() != ''){
		filters.priceMax = parseInt($('#priceMax').val());
	}
	
	if($('#priceMin').val() != undefined && $('#priceMin').val() != ''){
		filters.priceMin=parseInt($('#priceMin').val());
	}
	
	$.bbq.pushState({'filters':filters});
}



